# -*- coding: utf-8 -*-
"""
Created on 15-12-16 上午11:49
@file: cookie2.py
@author: Liangrong Li
@contact: liliangrong0@126.com
"""
def PrintCookie(url):
    import urllib2
    import cookielib
    #声明一个CookieJar对象实例来保存cookie
    cookie = cookielib.CookieJar()
    #利用urllib2库的HTTPCookieProcessor对象来创建cookie处理器
    handler = urllib2.HTTPCookieProcessor(cookie)
    #通过handler来构建opener
    opener = urllib2.build_opener(handler)
    #吃醋的open方法同urllib2的urlopen方法，也可以传入request
    resp = opener.open(url)
    #直接打印出cookie数据
    for item in cookie:
        print 'Name = ' + item.name
        print 'Value = ' + item.value

def SaveCookie(url):
    import cookielib
    import urllib2

    filename = 'cookie.txt'

    cookie = cookielib.MozillaCookieJar(filename)
    handler = urllib2.HTTPCookieProcessor(cookie)
    opener = urllib2.build_opener(handler)

    resp = opener.open(url)
    cookie.save(ignore_discard=True,ignore_expires=True)

def GetCookie(url):
    import cookielib
    import urllib2

    cookie = cookielib.MozillaCookieJar()
    cookie.load('cookie.txt',ignore_discard=True,ignore_expires=True)
    req = urllib2.Request(url)
    opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookie))
    resp = opener.open(req)
    html = resp.read()
    with open('baidu.html','w+') as f:
        f.write(html)
    # return resp.read()

if __name__ == '__main__':
    import time
    start = time.clock()

    url = "http://www.baidu.com"
    # a = PrintCookie()
    # print a
    #
    # SaveCookie()

    GetCookie(url)

    end = time.clock()
    print "run time is %f s" % (end-start)